<template>
  <div class="container">
    <h1 class="page-title">数据验证与追溯</h1>
    
    <div class="row">
      <div class="col-md-6">
        <div class="custom-card mb-4">
          <div class="card-header">
            <h3 class="mb-0">交易哈希查询</h3>
          </div>
          <div class="card-body">
            <p class="text-muted mb-4">通过交易哈希查询投资记录，验证记录的真实性。</p>
            <div class="mb-4">
              <label for="txHash" class="form-label">交易哈希</label>
              <input 
                type="text" 
                class="form-control custom-form-control" 
                id="txHash" 
                v-model="txHashQuery" 
                placeholder="输入交易哈希，如: 0x1234..."
              >
            </div>
            <button 
              class="custom-btn custom-btn-primary" 
              :disabled="!txHashQuery || loading" 
              @click="searchByTxHash"
            >
              <i class="bi bi-search"></i> 查询
            </button>
          </div>
        </div>
      </div>
      
      <div class="col-md-6">
        <div class="custom-card mb-4">
          <div class="card-header">
            <h3 class="mb-0">数据哈希验证</h3>
          </div>
          <div class="card-body">
            <p class="text-muted mb-4">验证投资记录的数据哈希是否一致，以确认数据完整性。</p>
            <div class="mb-4">
              <label for="investmentId" class="form-label">投资ID</label>
              <input 
                type="number" 
                class="form-control custom-form-control" 
                id="investmentId" 
                v-model="verifyForm.id" 
                placeholder="输入投资ID"
              >
            </div>
            <div class="mb-4">
              <label for="dataHash" class="form-label">数据哈希</label>
              <input 
                type="text" 
                class="form-control custom-form-control" 
                id="dataHash" 
                v-model="verifyForm.dataHash" 
                placeholder="输入数据哈希，如: 0x1234..."
              >
            </div>
            <button 
              class="custom-btn custom-btn-primary" 
              :disabled="!verifyForm.id || !verifyForm.dataHash || loading" 
              @click="verifyDataHash"
            >
              <i class="bi bi-shield-check"></i> 验证
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 加载中提示 -->
    <div v-if="loading" class="text-center my-5">
      <div class="spinner-border custom-spinner" role="status">
        <span class="visually-hidden">验证中...</span>
      </div>
      <p class="mt-3">处理请求中，请稍候...</p>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="error" class="alert alert-danger mb-4">
      {{ error }}
    </div>
    
    <!-- 交易哈希查询结果 -->
    <div v-if="txHashResult" class="custom-card mb-4">
      <div class="card-header" style="background-color: var(--info-color); color: white;">
        <h3 class="mb-0">交易哈希查询结果</h3>
      </div>
      <div class="card-body">
        <div class="mb-4">
          <h4 class="mb-3">投资记录详情</h4>
          <div class="table-responsive">
            <table class="custom-table">
              <tbody>
                <tr>
                  <th style="width: 30%">投资ID</th>
                  <td>{{ txHashResult.id }}</td>
                </tr>
                <tr>
                  <th>投资者地址</th>
                  <td class="text-monospace">{{ txHashResult.investor }}</td>
                </tr>
                <tr>
                  <th>金额</th>
                  <td>{{ txHashResult.amount }}</td>
                </tr>
                <tr>
                  <th>项目名称</th>
                  <td>{{ txHashResult.projectName }}</td>
                </tr>
                <tr>
                  <th>行业</th>
                  <td>{{ txHashResult.profession }}</td>
                </tr>
                <tr>
                  <th>数据哈希</th>
                  <td class="text-monospace">{{ formatHash(txHashResult.dataHash) }}</td>
                </tr>
                <tr>
                  <th>交易哈希</th>
                  <td class="text-monospace">{{ formatHash(txHashResult.txHash) }}</td>
                </tr>
                <tr>
                  <th>状态</th>
                  <td>
                    <span class="custom-badge" :style="{ 
                      backgroundColor: txHashResult.isActive ? 'var(--success-color)' : 'var(--danger-color)',
                      color: 'white'
                    }">
                      {{ txHashResult.isActive ? '有效' : '已删除' }}
                    </span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="d-flex gap-3">
          <router-link :to="`/detail/${txHashResult.id}`" class="custom-btn custom-btn-info">
            <i class="bi bi-info-circle"></i> 查看详情
          </router-link>
          <router-link :to="`/history/${txHashResult.dataHash}`" class="custom-btn custom-btn-secondary">
            <i class="bi bi-clock-history"></i> 查看历史版本
          </router-link>
        </div>
      </div>
    </div>
    
    <!-- 数据哈希验证结果 -->
    <div v-if="verifyResult !== null" class="custom-card mb-4">
      <div class="card-header" :style="{
        backgroundColor: verifyResult ? 'var(--success-color)' : 'var(--danger-color)',
        color: 'white'
      }">
        <h3 class="mb-0">数据哈希验证结果</h3>
      </div>
      <div class="card-body">
        <div class="verification-result" :class="verifyResult ? 'success' : 'error'">
          <div class="result-icon">
            <i :class="verifyResult ? 'bi bi-check-circle-fill' : 'bi bi-x-circle-fill'"></i>
          </div>
          <div class="result-content">
            <h4 class="mb-3">{{ verifyResult ? '验证成功' : '验证失败' }}</h4>
            <p class="mb-4">
              {{ verifyResult 
                ? '数据哈希验证通过，表明此投资记录数据未被篡改。' 
                : '数据哈希验证失败，记录可能已被篡改或提供的哈希不正确。' 
              }}
            </p>
            <div class="verification-details">
              <p class="mb-2">
                <strong>投资ID:</strong> 
                <span class="custom-badge" style="background-color: var(--accent-color); color: white;">
                  {{ verifyForm.id }}
                </span>
              </p>
              <p class="mb-0">
                <strong>提交的数据哈希:</strong> 
                <span class="text-monospace">{{ formatHash(verifyForm.dataHash) }}</span>
              </p>
            </div>
          </div>
        </div>
        <div class="mt-4" v-if="verifyResult">
          <router-link :to="`/detail/${verifyForm.id}`" class="custom-btn custom-btn-info">
            <i class="bi bi-info-circle"></i> 查看投资详情
          </router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import '../assets/styles.css';

export default {
  name: 'VerificationView',
  setup() {
    const store = useStore();
    const router = useRouter();
    
    // 表单数据
    const txHashQuery = ref('');
    const verifyForm = ref({
      id: '',
      dataHash: ''
    });
    
    // 结果
    const txHashResult = ref(null);
    const verifyResult = ref(null);
    
    // 加载状态和错误信息
    const loading = computed(() => store.getters.isLoading);
    const error = computed(() => store.getters.errorMessage);
    
    // 通过交易哈希查询
    const searchByTxHash = async () => {
      // 清除之前的结果
      txHashResult.value = null;
      verifyResult.value = null;
      
      if (!txHashQuery.value) return;
      
      // 处理可能的哈希前缀
      const txHash = txHashQuery.value.startsWith('0x') 
        ? txHashQuery.value 
        : `0x${txHashQuery.value}`;
      
      const result = await store.dispatch('getInvestmentByTxHash', txHash);
      if (result) {
        txHashResult.value = result;
      }
    };
    
    // 验证数据哈希
    const verifyDataHash = async () => {
      // 清除之前的结果
      txHashResult.value = null;
      verifyResult.value = null;
      
      if (!verifyForm.value.id || !verifyForm.value.dataHash) return;
      
      // 处理可能的哈希前缀
      const dataHash = verifyForm.value.dataHash.startsWith('0x') 
        ? verifyForm.value.dataHash 
        : `0x${verifyForm.value.dataHash}`;
      
      const result = await store.dispatch('verifyDataHash', {
        id: verifyForm.value.id,
        dataHash: dataHash
      });
      
      if (result) {
        verifyResult.value = result.verified;
      }
    };
    
    // 格式化哈希显示
    const formatHash = (hash) => {
      if (!hash) return '';
      
      // 将16进制字节数组转换为字符串
      let hashStr = '';
      if (Array.isArray(hash)) {
        // 转换字节数组为16进制字符串
        hashStr = '0x' + Array.from(hash).map(b => {
          // 确保是数字
          let num = typeof b === 'number' ? b : parseInt(b);
          // 避免负数问题（byte是有符号的）
          if (num < 0) num += 256;
          return num.toString(16).padStart(2, '0');
        }).join('');
      } else if (typeof hash === 'string') {
        hashStr = hash.startsWith('0x') ? hash : `0x${hash}`;
      } else {
        return 'Invalid hash';
      }
      
      return hashStr;
    };
    
    return {
      txHashQuery,
      verifyForm,
      txHashResult,
      verifyResult,
      loading,
      error,
      searchByTxHash,
      verifyDataHash,
      formatHash
    };
  }
}
</script>

<style scoped>
.verification-result {
  background-color: var(--light-cream);
  border-radius: 12px;
  padding: 2rem;
  display: flex;
  gap: 2rem;
  align-items: flex-start;
}

.verification-result.success .result-icon {
  color: var(--success-color);
}

.verification-result.error .result-icon {
  color: var(--danger-color);
}

.result-icon {
  font-size: 3rem;
  line-height: 1;
}

.result-content {
  flex: 1;
}

.verification-details {
  background-color: var(--white);
  padding: 1.5rem;
  border-radius: 8px;
  margin-top: 1rem;
}

.verification-details strong {
  color: var(--accent-color);
  font-weight: 600;
  margin-right: 0.5rem;
}

.text-monospace {
  font-family: monospace;
  font-size: 0.875rem;
  background-color: var(--light-cream);
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
}

/* 表格样式覆盖 */
.custom-table th {
  font-weight: 600;
  color: var(--accent-color);
}

/* 加载状态样式 */
.custom-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

/* 间距调整 */
.gap-3 {
  gap: 1rem;
}
</style> 